package com.freecloud.plug.mybatis.plugins;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.freecloud.common.LoggerUtil;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;

/**
 * 打印sql执行时间
 * @Author: maomao
 * @Date: 2021-04-09 16:21
 */
@Intercepts({
        @Signature(type = StatementHandler.class, //表示要拦截的接口类型
                method = "query",  //表示要拦截接口的对应方法
                args = {Statement.class, ResultHandler.class} //表示拦截方法对应的参数列表，反射时使用（解决方法重载问题）
                )
})
public class SQLExecuteTimeInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        TimeInterval timeInterval = DateUtil.timer();

        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();

        LoggerUtil.printThread("获取到的sql： " + boundSql.getSql());

        try {
            return invocation.proceed();
        }finally {
            LoggerUtil.printThread("sql执行时间：" + timeInterval.intervalSecond());
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {
        String name = properties.getProperty("name");
        LoggerUtil.printThread("打印sql执行时间 ： name = " + name);
    }
}
